import 'dart:convert';

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_wanandroid/common/api.dart';
import 'package:flutter_wanandroid/entity/article_entity.dart';
import 'package:flutter_wanandroid/httpUtils/http_util.dart';
import 'package:flutter_wanandroid/pages/flutter_webview.dart';
import 'package:flutter_wanandroid/res/colors.dart';
import 'package:fluttertoast/fluttertoast.dart';

import '../http/tree_entity.dart';

class TreeDetailPage extends StatefulWidget {
  final String title;
  final int currentIndex;

  TreeDetailPage({Key? key, required this.title, required this.currentIndex});

  @override
  State<TreeDetailPage> createState() => _TreeDetailPageState();
}

class _TreeDetailPageState extends State<TreeDetailPage>
    with TickerProviderStateMixin {
  TabController? _tabController;
  List<ChildrenBean> _data = [];
  EasyRefreshController? _easyRefreshController;
  int _currentIndex = 0;
  int _page = 0;
  List<DatasBean> _article = [];
  bool hasMore = true;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 0, vsync: this);
    _easyRefreshController = EasyRefreshController(
        controlFinishLoad: true, controlFinishRefresh: true);
    _tabController?.addListener(() {
      _onTabChanged();
    });
    getHttp();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).primaryColor,
        title: Text(
          widget.title,
          style: const TextStyle(color: Colors.white),
        ),
        bottom: TabBar(
          controller: _tabController,
          indicatorColor: Colors.white,
          labelColor: Colors.white,
          labelStyle: TextStyle(fontSize: 16),
          unselectedLabelColor: Colors.white60,
          unselectedLabelStyle: TextStyle(fontSize: 14),
          isScrollable: true,
          //indicator与文字同宽
          indicatorSize: TabBarIndicatorSize.label,
          tabs: _data.map((e) {
                return Tab(text: e.name ?? "");
              }).toList(),
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: _data.map((e) {
              return EasyRefresh(
                controller: _easyRefreshController,
                onRefresh: () async {
                  Future.delayed(Duration(seconds: 1), () {
                    if (mounted) {
                      setState(() {
                        _page = 0;
                      });
                    }
                    getDetail();
                    _easyRefreshController?.finishRefresh(IndicatorResult.success);
                  });
                },
                onLoad: () async {
                  Future.delayed(Duration(seconds: 1), () {
                    if (mounted) {
                      setState(() {
                        _page++;
                      });
                    }
                    getMoreData();
                    _easyRefreshController?.finishLoad(hasMore
                        ? IndicatorResult.success
                        : IndicatorResult.noMore);
                  });
                },
                child: CustomScrollView(
                  slivers: [
                    SliverList(
                      delegate: SliverChildBuilderDelegate((context, index) {
                        return getRow(context, index);
                      }, childCount: _article.length),
                    ),
                  ],
                ),
              );
            }).toList(),
      ),
    );
  }

  Widget? getRow(BuildContext context, int index) {
    // if (index == 0) {
    //   return null;
    // }
    return GestureDetector(
      child: ListTile(
        leading: IconButton(
          icon: const Icon(
            Icons.favorite,
          ),
          onPressed: () {
            Fluttertoast.showToast(msg: "收藏");
          },
        ),
        title: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 10),
          child: Text(
            _article[index].title ?? "",
            style: const TextStyle(
                color: YColors.color_666,
                overflow: TextOverflow.ellipsis,
                fontSize: 14),
            maxLines: 2,
          ),
        ),
        subtitle: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
          child: Row(
            children: [
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 10),
                constraints: const BoxConstraints(maxWidth: 150),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(20),
                  border: Border.all(
                      color: Theme.of(context).primaryColor, width: 1),
                ),
                child: Text(
                  widget.title,
                  style: TextStyle(color: Theme.of(context).primaryColor),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              )
            ],
          ),
        ),
        trailing: const Icon(Icons.chevron_right),
      ),
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => FlutterWebView(
                title: _article[index].title ?? "", uri: _article[index].link),
          ),
        );
      },
    );
  }

  void getHttp() async {
    var name = await HttpUtil().get(Api.TREE);
    Map<String, dynamic> map = json.decode(name.toString());
    TreeEntity? treeEntity = TreeEntity.fromMap(map);
    if (treeEntity != null && treeEntity.data != null) {
      if (mounted) {
        setState(() {
          _currentIndex = widget.currentIndex;
          _data = treeEntity.data?[_currentIndex].children ?? [];
          _tabController = TabController(length: _data.length, vsync: this);

        });
        getDetail();
        //controller添加监听
        _tabController?.addListener(() => _onTabChanged());
        //选中指定下标
        _tabController?.animateTo(_currentIndex);
      }
    }
  }

  void getDetail() async {
    var data = {"cid": _data[_currentIndex].id};
    var response =
        await HttpUtil().get("${Api.ARTICLE_LIST}$_page/json", data: data);
    Map<String, dynamic> map = json.decode(response.toString());
    ArticleEntity? articleEntity = ArticleEntity.fromMap(map);
    print(articleEntity.toString());
    if (articleEntity != null && articleEntity.data != null) {
      var data = articleEntity.data?.datas;
      if (data != null) {
        setState(() {
          _article = data;
        });
      }
    }
  }

  void getMoreData() async {
    var data = {"cid": _data[_currentIndex].id};
    var response =
        await HttpUtil().get(Api.ARTICLE_LIST + "$_page/json", data: data);
    Map<String, dynamic> map = json.decode(response.toString());
    ArticleEntity? articleEntity = ArticleEntity.fromMap(map);
    print(articleEntity.toString());
    if (articleEntity != null && articleEntity.data != null) {
      var data = articleEntity.data?.datas;
      if (data != null) {
        setState(() {
          _article.addAll(data);
          if (data.length < 20) {
            hasMore = false;
          } else {
            hasMore = true;
          }
        });
      }
    }
  }

  void _onTabChanged() {
    if (mounted && _tabController?.index.toDouble() == _tabController?.animation?.value) {
      setState(() {
        _currentIndex = _tabController?.index ?? 0;
      });
      getDetail();
    }
  }
}
